package com.huashizhaoxi.lionapp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huashizhaoxi.lionapp.entity.Product;
import com.huashizhaoxi.lionapp.entity.Result;
import com.huashizhaoxi.lionapp.service.Impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductServiceImpl productService;

    @GetMapping("/get/all/{pageNum}/{pageSize}")
    public Result getAllProduct(@PathVariable(value = "pageNum") Integer pageNum, @PathVariable(value = "pageSize") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productService.getAllProduct();
        if(productList == null) {
            return Result.error("获取所有产品失败");
        }else {
            PageInfo list = new PageInfo(productList);
            Map map = new HashMap();
            map.put("list", list.getList());
            map.put("size", list.getSize());
            map.put("total", list.getTotal());
            return Result.success("获取所有产品成功", map);
        }
    }

    @GetMapping("/get/search/{pageNum}/{pageSize}/{keyword}")
    public Result searchProduct(@PathVariable(value = "pageNum") Integer pageNum, @PathVariable(value = "pageSize") Integer pageSize, @PathVariable(value = "keyword") String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productService.searchProduct(keyword);
        if(productList == null) {
            return Result.error("搜索产品失败");
        }else {
            PageInfo list = new PageInfo(productList);
            Map map = new HashMap();
            map.put("list", list.getList());
            map.put("size", list.getSize());
            map.put("total", list.getTotal());
            return Result.success("搜索产品成功", map);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteProduct(@PathVariable(value = "id") Integer id) {
        int res = productService.deleteProduct(id);
        if(res == 0) {
            return Result.error("删除产品失败");
        }else {
            return Result.success("删除产品成功", null);
        }
    }

}
